package org.opens.javaskill.thread.api;

public class DeadLock {

    private final Object lock = new Object();

    private OtherService otherService;

    public DeadLock(OtherService otherService) {
        this.otherService = otherService;
    }

    public void m1() {
        synchronized (lock) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("m1 >>>");
            otherService.s1();
        }
    }

}

class OtherService {

    private final Object lock2 = new Object();

    private DeadLock deadLock;

    public void s1() {
        synchronized (lock2) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("s1 >>>");
            deadLock.m1();
        }
    }

    public DeadLock getDeadLock() {
        return deadLock;
    }

    public void setDeadLock(DeadLock deadLock) {
        this.deadLock = deadLock;
    }
}

class DeadLockTest {

    public static void main(String[] args) {
        OtherService otherService = new OtherService();
        DeadLock deadLock = new DeadLock(otherService);
        otherService.setDeadLock(deadLock);

        new Thread() {

            @Override
            public void run() {
                while(true) {
                    deadLock.m1();
                }
            }

        }.start();

        new Thread() {

            @Override
            public void run() {
                while(true) {
                    otherService.s1();
                }
            }

        }.start();

    }

}
